package cn.fl.ass.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssTrailCarChannelService;
import cn.fl.ass.transform.AssTrailCarChannelVOTransform;
import cn.fl.ass.vo.AssTrailCarChannelVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import fl.ass.facade.api.IAssTrailCarApi;
import fl.ass.facade.api.IAssTrailCarChannelApi;
import fl.ass.facade.condition.AssTrailCarChannelQC;
import fl.ass.facade.condition.AssTrailCarMQueryCondition;
import fl.ass.facade.dto.AssTrailCarChannelDTO;
import fl.ass.facade.dto.AssTrailCarMDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 拖车渠道表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssTrailCarChannelServiceImpl implements IAssTrailCarChannelService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IAssTrailCarChannelService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	//@Autowired
	//private I自定义ApiService 自定义ApiService;

    @Autowired
    private IAssTrailCarChannelApi assTrailCarChannelApi;
    /**
     * 本地数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISysRegionApiService sysRegionApiService;

    /**
     * 拖车模块 API 暴露服务
     */
    @Autowired
    private IAssTrailCarApi assTrailCarApi;



	@Override
	public AssTrailCarChannelVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return null;
		}
		AssTrailCarChannelDTO dto = this.assTrailCarChannelApi.selectById(id);
		return AssTrailCarChannelVOTransform.toVO(dto);
	}

	@Override
	public Long add(AssTrailCarChannelVO entity) throws BaseException{
		if(null == entity){
			return null;
		}
		return this.assTrailCarChannelApi.add(AssTrailCarChannelVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			return false;
		}
		//return this.assTrailCarChannelApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(AssTrailCarChannelVO entity) throws BaseException{
		if(null == entity){
			return false;
		}
		return this.assTrailCarChannelApi.modify(AssTrailCarChannelVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
        Pager pager = this.assTrailCarChannelApi.searchListPage(page);
        List<AssTrailCarChannelDTO> resultList = (List<AssTrailCarChannelDTO>)pager.getResultList();
        if (CollectionUtils.isNotEmpty(resultList)) {
            List<AssTrailCarMDTO> assTrailCarMDTOS = null;
            List<String> rgnCdList = new ArrayList<>();
            List<Long> chnIdList = new ArrayList<>();
            for (AssTrailCarChannelDTO assTrailCarChannelDTO : resultList) {
                rgnCdList.add(assTrailCarChannelDTO.getRecordPrCd());
                chnIdList.add(assTrailCarChannelDTO.getId());
            }
            if (CollectionUtils.isNotEmpty(chnIdList)) {
                //查询总拖车数和费用
                AssTrailCarMQueryCondition assTrailCarMQueryCondition = new AssTrailCarMQueryCondition();
                assTrailCarMQueryCondition.setChannelIdList(chnIdList);
                // assTrailCarMQueryCondition.setIsDel(0);
                assTrailCarMQueryCondition.setBackStsCd("2");//已拖回状态
                assTrailCarMDTOS = assTrailCarApi.selectListByChnIds(assTrailCarMQueryCondition);
            }
            //地区
            Map<String, SysRegionDTO> rgnMap = this.sysRegionApiService.searchRegionByRgnCd(rgnCdList, CurrentThreadContext.getCurrentSysCd());
            //渠道类型
            Map<String, String> ChannelTypeCdMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_CST_TYP_CD); //项目类型名称
            for (AssTrailCarChannelDTO assTrailCarChannelDTO : resultList) {
                Integer backQtySum = 0;
                Double backAmtSum = 0D;
                assTrailCarChannelDTO.setChannelTypeCdStr(ChannelTypeCdMap.get(assTrailCarChannelDTO.getChannelTypeCd()));
                if (Objects.equals("ALL", assTrailCarChannelDTO.getRecordPrCd())) {
                    assTrailCarChannelDTO.setRecordPrCdStr("总部");
                }
                if(rgnMap.containsKey(assTrailCarChannelDTO.getRecordPrCd())){
                    SysRegionDTO dto = rgnMap.get(assTrailCarChannelDTO.getRecordPrCd());
                    assTrailCarChannelDTO.setRecordPrCdStr(dto.getRgnNm());
                }

                //处理拖车数量以及拖车费用
                if (CollectionUtils.isNotEmpty(assTrailCarMDTOS)) {
                    for (AssTrailCarMDTO assTrailCarMDTO : assTrailCarMDTOS) {
                        if (Objects.equals(assTrailCarMDTO.getChannelId(), assTrailCarChannelDTO.getId())) {
                            backQtySum += assTrailCarMDTO.getBackQty();//拖车数
                            backAmtSum += DecimalUtils.convertFenToYuan(assTrailCarMDTO.getBackAmt());//合计拖车费用
                        }
                    }
                    assTrailCarChannelDTO.setBackQtySum(backQtySum);
                    assTrailCarChannelDTO.setBackAmtSum(backAmtSum);
                }
            }
        }
        pager.setResultList(resultList);
        return pager;
    }

    @Override
    public boolean enAbleChannel(Long id, Integer isValidInt) throws BaseException {
        if(null == id){
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
        };
        return this.assTrailCarChannelApi.enAbleChannel(id, isValidInt);
    }

    @Override
    public List<KeyValueVO> searchCdList(String grpCd) throws BaseException {
        return this.getKvList(grpCd);
    }

    @Override
    public List<AssTrailCarChannelVO> getChnByPrCd(String recordPrCd, String isVaildFlag) throws BaseException {
        if (StringUtils.isEmpty(recordPrCd)) return null;
        List<AssTrailCarChannelVO> assTrailCarChannelVOS = null;
        try {
            AssTrailCarChannelQC assTrailCarChannelQC = new AssTrailCarChannelQC();
            assTrailCarChannelQC.setRecordPrCd(recordPrCd);
            if (Objects.equals(isVaildFlag, "true")) {
                assTrailCarChannelQC.setIsDel(0);
                assTrailCarChannelQC.setIsValid(1);
            }
            List<AssTrailCarChannelDTO> assTrailCarChannel = this.assTrailCarChannelApi.searchList(assTrailCarChannelQC);
            assTrailCarChannelVOS = AssTrailCarChannelVOTransform.toVOList(assTrailCarChannel);
            if (CollectionUtils.isNotEmpty(assTrailCarChannelVOS)) {
                //渠道类型
                Map<String, String> ChannelTypeCdMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_CST_TYP_CD); //项目类型名称
                for (AssTrailCarChannelVO assTrailCarChannelVO : assTrailCarChannelVOS) {
                    assTrailCarChannelVO.setChannelTypeCdStr(ChannelTypeCdMap.get(assTrailCarChannelVO.getChannelTypeCd()));
                }
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("根据省获取拖车单位名称失败 BaseException").setThrowable(e).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("根据省获取拖车单位名称失败 Exception").setThrowable(e).info();
        }
        return assTrailCarChannelVOS;
    }


    /**
     * 根据字典中代码组值获取组员集合
     * @param grpCd 代码组值
     * @return 集合
     */
    private List<KeyValueVO> getKvList(String grpCd){
        List<KeyValueVO> kvList = new ArrayList<>();
        try {
            List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
            if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
                for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
                    KeyValueVO keyValueVO = new KeyValueVO();
                    keyValueVO.setKey(sysDictionaryDTO.getCode());
                    keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
                    kvList.add(keyValueVO);
                }
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("获取字典项组失败 BaseException").setThrowable(e).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("获取字典项组失败 Exception").setThrowable(e).info();
        }
        return kvList;
    }


}
